{% extends 'base.html' %}
{% load static %}

{% block title %}SKU管理 - 维修管理系统{% endblock %}

{% block content %}
<div class="d-flex justify-content-between align-items-center mb-4">
    <h2>SKU管理</h2>
    <div>
        <a href="{% url 'spare_parts:sku_add' %}" class="btn btn-primary me-2">
            <i class="bi bi-plus-circle"></i> 新增备件
        </a>
        <a href="{% url 'spare_parts:category_list' %}" class="btn btn-outline-secondary me-2">
            <i class="bi bi-diagram-3"></i> 分类管理
        </a>
        <a href="{% url 'spare_parts:inventory_list' %}" class="btn btn-outline-secondary">
            <i class="bi bi-box-seam"></i> 库存管理
        </a>
    </div>
</div>

<!-- 搜索过滤 -->
<div class="card mb-4">
    <div class="card-body">
        <form method="get" class="row g-3">
            <div class="col-md-4">
                <label class="form-label">SKU编号</label>
                <input type="text" name="sku" class="form-control" placeholder="搜索SKU编号" value="{{ request.GET.sku }}">
            </div>
            <div class="col-md-4">
                <label class="form-label">备件名称</label>
                <input type="text" name="name" class="form-control" placeholder="搜索备件名称" value="{{ request.GET.name }}">
            </div>
            <div class="col-md-4">
                <label class="form-label">分类</label>
                <select name="category" class="form-select">
                    <option value="">所有分类</option>
                    {% for category in categories %}
                    <option value="{{ category.id }}" {% if request.GET.category == category.id|stringformat:"s" %}selected{% endif %}>
                        {{ category.name }}
                    </option>
                    {% endfor %}
                </select>
            </div>
            <div class="col-md-4">
                <label class="form-label">状态</label>
                <select name="status" class="form-select">
                    <option value="">所有状态</option>
                    <option value="active" {% if request.GET.status == 'active' %}selected{% endif %}>正常</option>
                    <option value="discontinued" {% if request.GET.status == 'discontinued' %}selected{% endif %}>停产</option>
                    <option value="obsolete" {% if request.GET.status == 'obsolete' %}selected{% endif %}>淘汰</option>
                </select>
            </div>
            <div class="col-md-4">
                <label class="form-label">库存状态</label>
                <select name="stock_status" class="form-select">
                    <option value="">所有状态</option>
                    <option value="low" {% if request.GET.stock_status == 'low' %}selected{% endif %}>库存不足</option>
                    <option value="normal" {% if request.GET.stock_status == 'normal' %}selected{% endif %}>正常库存</option>
                    <option value="high" {% if request.GET.stock_status == 'high' %}selected{% endif %}>库存过高</option>
                </select>
            </div>
            <div class="col-md-4 d-flex align-items-end">
                <button type="submit" class="btn btn-primary me-2">
                    <i class="bi bi-search"></i> 搜索
                </button>
                <a href="{% url 'spare_parts:sku_management' %}" class="btn btn-outline-secondary">
                    <i class="bi bi-arrow-clockwise"></i> 重置
                </a>
            </div>
        </form>
    </div>
</div>

<!-- SKU列表 -->
<div class="card">
    <div class="card-body">
        {% if spare_parts %}
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>SKU编号</th>
                        <th>备件名称</th>
                        <th>型号规格</th>
                        <th>分类</th>
                        <th>供应商</th>
                        <th>单价</th>
                        <th>当前库存</th>
                        <th>库存状态</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for part in spare_parts %}
                    <tr>
                        <td>
                            <strong>{{ part.part_number }}</strong>
                            {% if part.supplier_part_number %}
                            <br><small class="text-muted">供应商: {{ part.supplier_part_number }}</small>
                            {% endif %}
                        </td>
                        <td>{{ part.name }}</td>
                        <td>{{ part.model }}</td>
                        <td>{{ part.category.name|default:"-" }}</td>
                        <td>{{ part.supplier.name|default:"-" }}</td>
                        <td>¥{{ part.unit_price }}</td>
                        <td>
                            {{ part.current_stock }} {{ part.unit }}
                            {% if part.is_low_stock %}
                            <span class="badge bg-danger ms-1">低</span>
                            {% elif part.is_over_stock %}
                            <span class="badge bg-warning ms-1">高</span>
                            {% endif %}
                        </td>
                        <td>
                            <span class="badge 
                                {% if part.stock_status == 'low' %}bg-danger
                                {% elif part.stock_status == 'high' %}bg-warning
                                {% else %}bg-success{% endif %}">
                                {{ part.get_stock_status_display }}
                            </span>
                        </td>
                        <td>
                            <span class="badge 
                                {% if part.status == 'active' %}bg-success
                                {% elif part.status == 'discontinued' %}bg-secondary
                                {% else %}bg-dark{% endif %}">
                                {{ part.get_status_display }}
                            </span>
                        </td>
                        <td>
                            <div class="btn-group btn-group-sm" role="group">
                                <button type="button" class="btn btn-outline-info view-details" 
                                        data-bs-toggle="modal" data-bs-target="#skuModal"
                                        data-part-id="{{ part.id }}" title="查看详情">
                                    <i class="bi bi-eye"></i>
                                </button>
                                <a href="{% url 'spare_parts:sku_edit' part.id %}" 
                                   class="btn btn-outline-primary" title="编辑">
                                    <i class="bi bi-pencil"></i>
                                </a>
                                <a href="{% url 'spare_parts:inventory_add' %}?spare_part={{ part.id }}" 
                                   class="btn btn-outline-success" title="库存操作">
                                    <i class="bi bi-box-arrow-in-down"></i>
                                </a>
                                <form method="post" action="{% url 'spare_parts:sku_delete' part.id %}" style="display: inline;">
                                    {% csrf_token %}
                                    <button type="submit" class="btn btn-outline-danger" 
                                            title="删除" onclick="return confirm('确定要删除这个备件吗？')">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </form>
                            </div>
                        </td>
                    </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>

        <!-- 分页 -->
        {% if is_paginated %}
        <nav aria-label="Page navigation" class="mt-4">
            <ul class="pagination justify-content-center">
                {% if page_obj.has_previous %}
                <li class="page-item">
                    <a class="page-link" href="?page={{ page_obj.previous_page_number }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">上一页</a>
                </li>
                {% endif %}
                
                {% for num in page_obj.paginator.page_range %}
                <li class="page-item {% if page_obj.number == num %}active{% endif %}">
                    <a class="page-link" href="?page={{ num }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">{{ num }}</a>
                </li>
                {% endfor %}
                
                {% if page_obj.has_next %}
                <li class="page-item">
                    <a class="page-link" href="?page={{ page_obj.next_page_number }}{% for key, value in request.GET.items %}{% if key != 'page' %}&{{ key }}={{ value }}{% endif %}{% endfor %}">下一页</a>
                </li>
                {% endif %}
            </ul>
        </nav>
        {% endif %}

        {% else %}
        <div class="text-center py-5">
            <i class="bi bi-box-seam display-1 text-muted"></i>
            <h5 class="mt-3">暂无备件数据</h5>
            <p class="text-muted">请先添加备件或调整搜索条件</p>
        </div>
        {% endif %}
    </div>
</div>

<!-- 统计信息 -->
<div class="row mt-4">
    <div class="col-md-3">
        <div class="card bg-primary text-white">
            <div class="card-body text-center">
                <h5 class="card-title">{{ total_count }}</h5>
                <p class="card-text">总备件数</p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card bg-success text-white">
            <div class="card-body text-center">
                <h5 class="card-title">{{ active_count }}</h5>
                <p class="card-text">正常状态</p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card bg-danger text-white">
            <div class="card-body text-center">
                <h5 class="card-title">{{ low_stock_count }}</h5>
                <p class="card-text">库存不足</p>
            </div>
        </div>
    </div>
    <div class="col-md-3">
        <div class="card bg-warning text-white">
            <div class="card-body text-center">
                <h5 class="card-title">{{ over_stock_count }}</h5>
                <p class="card-text">库存过高</p>
            </div>
        </div>
    </div>
</div>

<!-- SKU详情模态框 -->
<div class="modal fade" id="skuModal" tabindex="-1" aria-labelledby="skuModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="skuModalLabel">备件详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body" id="skuModalBody">
                <div class="text-center">
                    <div class="spinner-border" role="status">
                        <span class="visually-hidden">加载中...</span>
                    </div>
                    <p class="mt-2">加载备件详情...</p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <a href="#" class="btn btn-primary" id="editSkuBtn">编辑</a>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const skuModal = document.getElementById('skuModal');
    const skuModalBody = document.getElementById('skuModalBody');
    const editSkuBtn = document.getElementById('editSkuBtn');
    
    // 处理查看详情按钮点击
    document.querySelectorAll('.view-details').forEach(button => {
        button.addEventListener('click', function() {
            const partId = this.getAttribute('data-part-id');
            loadSkuDetails(partId);
        });
    });
    
    // 加载SKU详情
    function loadSkuDetails(partId) {
        // 显示加载中
        skuModalBody.innerHTML = `
            <div class="text-center">
                <div class="spinner-border" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
                <p class="mt-2">加载备件详情...</p>
            </div>
        `;
        
        // 设置编辑按钮链接
        editSkuBtn.href = `/spare-parts/sku/${partId}/edit/`;
        
        // 使用AJAX加载详情
        fetch(`/spare-parts/sku/${partId}/`)
            .then(response => {
                if (!response.ok) {
                    throw new Error('加载失败');
                }
                return response.text();
            })
            .then(html => {
                // 从返回的HTML中提取主要内容
                const parser = new DOMParser();
                const doc = parser.parseFromString(html, 'text/html');
                const content = doc.querySelector('.content');
                
                if (content) {
                    skuModalBody.innerHTML = content.innerHTML;
                } else {
                    skuModalBody.innerHTML = '<div class="alert alert-danger">加载详情失败</div>';
                }
            })
            .catch(error => {
                console.error('Error:', error);
                skuModalBody.innerHTML = `
                    <div class="alert alert-danger">
                        <h5>加载失败</h5>
                        <p>无法加载备件详情，请刷新页面重试。</p>
                    </div>
                `;
            });
    }
    
    // 模态框关闭时清空内容
    skuModal.addEventListener('hidden.bs.modal', function() {
        skuModalBody.innerHTML = `
            <div class="text-center">
                <div class="spinner-border" role="status">
                    <span class="visually-hidden">加载中...</span>
                </div>
                <p class="mt-2">加载备件详情...</p>
            </div>
        `;
    });
});
</script>
{% endblock %}
